package main

import (
	"fmt"
	"log"
	"net"

	"github.com/gin-gonic/gin"
	"github.com/hashicorp/consul/api"

	"gateway/handlers"
)

func main() {
	// 创建Gin路由器
	router := gin.Default()

	// 设置路由
	handlers.SetupRoutes(router)

	// 注册服务到Consul
	if err := registerToConsul(); err != nil {
		log.Printf("Failed to register to Consul: %v", err)
	}

	// 启动网关服务
	log.Println("Gateway server starting on :8081")
	if err := router.Run(":8081"); err != nil {
		log.Fatalf("Failed to start gateway: %v", err)
	}
}

// registerToConsul 注册服务到Consul
func registerToConsul() error {
	// 创建Consul客户端配置
	config := api.DefaultConfig()
	config.Address = "192.168.17.135:8500"

	// 创建Consul客户端
	client, err := api.NewClient(config)
	if err != nil {
		return fmt.Errorf("failed to create consul client: %w", err)
	}

	// 获取本机IP地址
	localIP, err := getLocalIP()
	if err != nil {
		return fmt.Errorf("failed to get local IP: %w", err)
	}

	// 服务注册信息
	serviceID := "gateway-service-8084"
	serviceName := "gateway-service"
	servicePort := 8084

	// 创建服务注册对象
	registration := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    serviceName,
		Tags:    []string{"gateway", "api", "http"},
		Port:    servicePort,
		Address: localIP,
		Check: &api.AgentServiceCheck{
			HTTP:                           fmt.Sprintf("http://%s:%d/health", localIP, servicePort),
			Timeout:                        "10s",
			Interval:                       "30s",
			DeregisterCriticalServiceAfter: "60s",
		},
	}

	// 注册服务
	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		return fmt.Errorf("failed to register service: %w", err)
	}

	log.Printf("Successfully registered gateway service to Consul: %s:%d", localIP, servicePort)
	return nil
}

// getLocalIP 获取本机IP地址
func getLocalIP() (string, error) {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return "", err
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)
	return localAddr.IP.String(), nil
}
